<?php

class Login_Model extends Model {

    public function __construct() {
        parent::__construct();
    }

    public function signin() {
        $form = new Form();
        try {
            $form -> post('login') 
                    -> val('minlength', 3) 
                    -> val('maxlength', 8)
                    ->val('alnum') 
                  -> post('password') 
                    -> val('minlength', 4) 
                    -> val('maxlength', 8)
                    ->val('alnum')
                  ->post('remember');
            $form -> submit();
            $data = $form -> fetch();
        } catch (Exception $e) {
            return $e -> getMessage();
        }
        

        $row = $this -> db -> select("SELECT idUser, role, firstName FROM user WHERE 
                userName = :userName AND password = :password", array(':userName' => $data['login'], ':password' => Hash::create('sha256', $data['password'], HASH_PASSWORD_KEY)));
        if (isset($row[0])) {
            Session::init();
            Session::set('user', $row[0]);
            if ( isset($data['remember']))
            {
                setcookie('login', $data['login'], time() + (86400 * 7), '/'); // 86400 = 1 day
            }  
        } else {
            return false;
        }
        return true;
    }
    
     public function create() {
        $form = new Form();
        try {
            $form   ->post('userName')
                        ->val('minlength', 3)
                        ->val('maxlength', 16)
                        ->val('alnum')
                    ->post('password')
                        ->val('minlength', 6)
                        ->val('maxlength', 16)
                        ->val('alnum')
                    ->post('firstName')
                        ->val('minlength', 2)
                        ->val('maxlength', 22)
                        ->val('alnum')
                    ->post('lastName')
                        ->val('minlength', 2)
                        ->val('maxlength', 22)
                        ->val('alnum')
                    ->post('email')
                        ->val('email')
                    ->submit();
        } catch (Exception $e) {
            return $e->getMessage();
        }
        $data = $form->fetch();
        $data['password'] = Hash::create('sha256', $data['password'], HASH_PASSWORD_KEY);

        $this->db->insert('user', $data);
        return 'good';
    }
}
